from odoo import api, fields, models, _
from odoo.exceptions import  ValidationError


class MrpWorkorder(models.Model):
    _inherit = 'mrp.workorder'

    s_is_lock = fields.Boolean(string='Lock or Unlock', related='production_id.is_lock')
    lock_reason = fields.Html(string='Lock Reason', related='production_id.lock_reason', copy=False)

    # @api.depends('production_id.is_lock')
    # def _compute_is_lock(self):
    #     for rec in self:
    #         def top_production(production):
    #             # 最顶层production
    #             ids = production._get_sources()
    #             parent_ids = [rec for rec in ids]
    #             if not parent_ids:
    #                 origin = production
    #             else:
    #                 production = parent_ids[0]
    #                 while parent_ids:
    #                     production = parent_ids.pop()
    #                     ids = production._get_sources()
    #                     parent_ids = [rec for rec in ids]
    #                 origin = production
    #             return origin
    #         top_production = top_production(rec.production_id)
    #         is_lock = False
    #         if rec.is_lock:
    #             is_lock = True
    #         elif rec.production_id.is_lock or top_production.is_lock:
    #             is_lock = True
    #         elif top_production.product_id.product_tmpl_id.s_disable_workorder:
    #             is_lock = True
    #         rec.is_lock = is_lock

    def button_start(self):
        for rec in self:
            if rec.s_is_lock:
                raise ValidationError('订单前工序或厂编已锁定不允许过数, 请联系相关部门！')
        return super().button_start()

    def button_finish(self):
        for rec in self:
            if rec.s_is_lock:
                raise ValidationError('订单前工序或厂编已锁定不允许过数, 请联系相关部门！')
        return super().button_finish()

    def button_pending(self):
        for rec in self:
            if rec.s_is_lock:
                raise ValidationError('订单前工序或厂编已锁定不允许过数, 请联系相关部门！')
        return super().button_pending()

    def action_mark_as_done(self):
        for rec in self:
            if rec.s_is_lock:
                raise ValidationError('订单前工序或厂编已锁定不允许过数, 请联系相关部门！')
        return super().action_mark_as_done()

    def button_unblock(self):
        for rec in self:
            if rec.s_is_lock:
                raise ValidationError('订单前工序或厂编已锁定不允许过数, 请联系相关部门！')
        return super().button_unblock()
